#include "sdlStringInput.h"

using std::string;
using ColorTextImage::Colors;

sdlStringInput::sdlStringInput(int size, filter modo, Colors color){
	this->text = "";
	this->modo = modo;
	this->color = color;
	this->maxLength = 15;
	this->mInput = ambos;
    this->font.load("font.ttf", size);
    string temp;
    temp.replace(0,temp.length(),this->maxLength,' ');
	this->renderText(this->font, temp, this->color);
}

void sdlStringInput::setFilter(filter modo){
	this->modo = modo;
}

void sdlStringInput::setColor(Colors color){
	this->color = color;
}

string sdlStringInput::getTexto(){
	return this->text;
}

void sdlStringInput::setModoInput(modoInput mi){
	this->mInput = mi;
}

void sdlStringInput::resetText(){
	this->text = "";
}

void sdlStringInput::adaptarAModo(const string& texto, string& temp){
	if (this->modo == invisible){
		temp.replace(0,temp.length(),this->text.length(),' ');
	} else if (this->modo == asterisk){
		temp.replace(0,temp.length(),this->text.length(),'*');
	} else {
		temp = this->text;
	}
}

void sdlStringInput::setMaxLength(unsigned length){
	this->maxLength = length;
}

bool sdlStringInput::handleEvent(const SDL_Event& event){
	bool b = false; //es true si pudo manejar el evento
	if (event.type == SDL_KEYDOWN){
		string temp = text;
		if (event.key.keysym.sym == SDLK_UNDERSCORE){
			SDL_EnableUNICODE(SDL_ENABLE);
			temp = '_';
			this->renderText(this->font, temp, this->color);
			b = true;
		} else if ((event.key.keysym.sym == SDLK_BACKSPACE) &&
		(text.length() != 0)){
			text.erase(text.length() - 1);
			b = true;
		} else if (event.key.keysym.sym == SDLK_RETURN){
			this->adaptarAModo(this->text,temp);
			if (temp.empty()){temp = " ";}
			this->renderText(this->font, temp, this->color);
			SDL_EnableUNICODE(SDL_DISABLE);
			return true;
		} else if (text.length() < this->maxLength) {
			if ((event.key.keysym.unicode >= (Uint16)'0') &&
			(event.key.keysym.unicode <= (Uint16)'9') && this->mInput!=letras){
				text += (char)event.key.keysym.unicode;
				b = true;
			} else if ((event.key.keysym.unicode >= (Uint16)'A') &&
			(event.key.keysym.unicode <= (Uint16)'Z') && this->mInput!=numeros){
				text += (char)event.key.keysym.unicode;
				b = true;
			} else if((event.key.keysym.unicode >= (Uint16)'a') &&
			(event.key.keysym.unicode <= (Uint16)'z') && this->mInput!=numeros){
				text += (char)event.key.keysym.unicode;
				b = true;
			}
        }
		if (text.empty()){
			temp = '_';
			temp.replace(1,temp.length(),this->maxLength,' ');
			this->renderText(this->font, temp, this->color);
		} else if (text != temp){
			this->adaptarAModo(text,temp);
			temp += '_';
			this->renderText(this->font, temp, this->color);
        }
    }
    return b;
}

sdlStringInput::~sdlStringInput(){
	SDL_EnableUNICODE(SDL_DISABLE);
}
